package cn.edu.zafu.bigdata.bd121.student.command;

import cn.edu.zafu.bigdata.bd121.student.cli.CliMain;
import cn.edu.zafu.bigdata.bd121.student.constant.StudentInfoConst;
import cn.hutool.json.JSONUtil;

import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 命令模版类
 *
 * @author 202211090121
 */
public abstract class BaseCommand {

    /**
     * 执行命令
     */
    public void execute() {
        handleUserInput();
        updateDataBase();
    }

    /**
     * 读取用户输入
     */
    protected void handleUserInput() {
        System.err.println("该命令不支持!");
    }

    /**
     * 更新本地数据库
     */
    protected void updateDataBase() {
        String jsonStr = JSONUtil.toJsonStr(CliMain.studentList);
        try (FileOutputStream fileOutputStream = new FileOutputStream(StudentInfoConst.DB_PATH)) {
            fileOutputStream.write(jsonStr.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}
